package com.example.goodpet.chat.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.goodpet.R;
import com.example.goodpet.bean.ResponseBody;
import com.example.goodpet.chat.adapter.UserAdapter;
import com.example.goodpet.common.EndlessRecyclerOnScrollListener;
import com.example.goodpet.common.LoadMoreWrapper;
import com.example.goodpet.db.DatabaseHelper;
import com.example.goodpet.db.dao.GoodpetHistoryDAO;
import com.example.goodpet.db.dao.UserDAO;
import com.example.goodpet.db.entity.User;
import com.example.goodpet.service.UserService;
import com.example.goodpet.utils.ActivityManager;
import com.example.goodpet.utils.MyApplication;
import com.example.goodpet.utils.RetrofitSingleton;
import com.example.goodpet.utils.SecurityUtils;
import com.example.goodpet.utils.TimeSeed;
import com.example.goodpet.utils.UIUtils;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.easeui.adapter.EaseBaseRecyclerViewAdapter;
import com.hyphenate.easeui.constants.EaseConstant;
import com.hyphenate.easeui.interfaces.OnItemClickListener;
import com.hyphenate.easeui.widget.EaseRecyclerView;
import com.zackratos.ultimatebarx.ultimatebarx.java.UltimateBarX;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ChatSearchActivity extends FragmentActivity {
    protected EditText query;
    protected TextView tvCancel;
    private ImageButton searchClear;
    protected RecyclerView rvList;
    protected UserAdapter adapter;
    protected LoadMoreWrapper loadMoreWrapper;

    private List<User> data;
    private boolean isFromLocal=true;
    private String search="";

    private UserDAO userDAO;
    private StringBuffer reNickname;
    private UserService userService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat_search);
        UltimateBarX.statusBarOnly(this)
                .fitWindow(true)
                .colorRes(R.color.ic_back_background)
                .light(true)
                .apply();
        ActivityManager.getInstance().addActivity(this);
        query = findViewById(R.id.query);
        searchClear = findViewById(R.id.search_clear);
        rvList = findViewById(R.id.rv_list);
        tvCancel = findViewById(R.id.tv_cancel);



        data=new ArrayList<>();

        initData();
        //让EditText获取焦点并弹出软键盘
        query.requestFocus();
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        initListener();
    }

    private void initListener() {
        query.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    searchClear.setVisibility(View.VISIBLE);
                } else {
                    searchClear.setVisibility(View.INVISIBLE);
                    data.clear();
                    loadMoreWrapper.setLoadState(loadMoreWrapper.LOADING_COMPLETE);
                }

            }
        });
        query.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if(actionId==EditorInfo.IME_ACTION_SEARCH/*(event != null && KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction())*/){
                    search = query.getText().toString().trim();
                    if(!TextUtils.isEmpty(search)) {
                        searchMessages(search);
                        //initData();
                    }
                    hideKeyboard();
                    return true;
                }
                return false;
            }
        });
        searchClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                query.getText().clear();
                data.clear();
                loadMoreWrapper.setLoadState(loadMoreWrapper.LOADING_COMPLETE);
            }
        });

        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }


    protected UserAdapter getAdapter(){
           return new UserAdapter(data,this);
    }

    public void searchMessages(String search){
        userDAO = DatabaseHelper.getInstance(this).getUserDAO();
        List<EMMessage> emMessages = EMClient.getInstance().chatManager().searchMsgFromDB(search, TimeSeed.Get(), 100, /*EaseConstant.DEFAULT_SYSTEM_MESSAGE_ID*/null, EMConversation.EMSearchDirection.UP);
        for (EMMessage emMessage : emMessages) {
            String s = SecurityUtils.unEncryptPhoneNumber(emMessage.getUserName());
            User user = userDAO.queryUser(s);
            //System.out.println("ChatSearchActivity.searchMessages"+user.getId());
            user.setSignature(((EMTextMessageBody)emMessage.getBody()).getMessage());
            data.add(user);
        }
        loadMoreWrapper.notifyItemRangeChanged(0,data.size());

    }

    public  void initData(){
        rvList.setLayoutManager(new LinearLayoutManager(this));
        rvList.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        adapter = getAdapter();
        loadMoreWrapper=new LoadMoreWrapper(adapter);
        rvList.setAdapter(loadMoreWrapper);
    }

    /**
     * hide keyboard
     */
    public void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm!=null&&getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null){
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }
}